/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.db.generator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import net.db.generator.utils.ClassGeneratorUtil;

/**
 *
 * @author abosancic
 */
public class JavaConnectionPropertiesWriter extends JavaBaseClassWriter {

    protected StringBuilder stringFile = null;
    protected java.util.Properties properties;

    public JavaConnectionPropertiesWriter() {
        super();
        stringFile = new StringBuilder();
    }

    public void setProperties(java.util.Properties properties) {
        this.properties = properties;
    }

    public void generateFile() {
        stringFile.append("# mysql\n");
        if (properties != null) {
            for (String key : properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                stringFile.append(key + "=" + value).append("\n");
            }
        }
        stringFile.append("#end mysql");
//        stringFile.append(
//                "driver=com.mysql.jdbc.Driver\n"
//                + "jdbcURL=jdbc:mysql://127.0.0.1:3306/test\n"
//                + "username=root\n"
//                + "password=abosancic\n"
//                + "preconnectCount=5\n"
//                + "maxIdleConnections=25\n"
//                + "maxConnections=25");
        // write this file
        writeFile();
    }

    protected final synchronized void writeFile() {

        try {

            String path = "." + File.separator + "src" + File.separator;
            if (getPackageName() != null) {
                path += getPackageName().replace(".", File.separator);
                new File(path).mkdirs();
            }

            FileWriter fstream = new FileWriter(path + File.separator + ClassGeneratorUtil.humanize(ClassGeneratorUtil.humanize(getClassName())) + ".properties");
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(stringFile.toString());
            //Close the output stream
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        stringFile = new StringBuilder();
    }
}
